package com.youmu.shop.coupon.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.exception.ParamException;
import com.mysql.jdbc.Connection;
import com.youmu.shop.common.utils.ConnectionsUtils;
import com.youmu.shop.coupon.bean.Coupon;
import com.youmu.shop.coupon.bean.CouponCodeBean;
import com.youmu.shop.coupon.dao.CouponDao;
import com.youmu.shop.coupon.service.CouponService;
import com.youmu.shop.coupon.vo.CouponVO;
import com.youmu.shop.param.CalculateFreightParam;
import com.youmu.shop.product.dao.ProductDao;


@Service
public class CouponServiceImpl implements CouponService {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	
    @Autowired
    private CouponDao couponDao;

    @Autowired
    private ProductDao productDao;
    
	@Override
	public List<CouponVO> findCoupon(Long userId,Integer status) {
		return couponDao.findCoupon(userId,status);
	}

	@Override
	public Double getCouponByCouponCodeId(Long id) {
		if(id == null){
			throw new ParamException("优惠劵id不能为空！");
		}
		return couponDao.getCouponByCouponCodeId(id);
	}

    /** 
     * @see com.youmu.shop.coupon.service.CouponService#findUsefulCouponIds()
     */
    @Override
    public List<Long> findUsefulCouponIds() {
        return couponDao.findUsefulCouponIds();
    }

    /** 
     * @see com.youmu.shop.coupon.service.CouponService#saveCouponForUser(java.util.List, long)
     */
    @Override
    public void saveCouponForUser(Long couponId, Long userId) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("couponId", couponId);
    	map.put("memberId", userId);
    	if(couponDao.selectCouponCodeByCouponIdAndMemberId(map) == null){
    		couponDao.saveCouponForUser(couponId,userId);
    	}
    }

	@Override
	public List<Coupon> selectCouponsForPlaceOrder(CalculateFreightParam calculateFreightParam) {
		String productIdString = calculateFreightParam.getProductIds();
		String productTotalPricesString = calculateFreightParam.getProductTotalPrices();
		Map<String, Object> map = new HashMap<String, Object>();
		List<Coupon> returnList = new ArrayList<Coupon>();
		if(productIdString.length() > 0){
			String[] productIds = productIdString.split(",");
			String[] productTotalPrices = productTotalPricesString.split(",");
			if(productIds.length != productTotalPrices.length){
				throw new RuntimeException("参数个数不对应");
			}
			map.put("userId", calculateFreightParam.getUserId());
			map.put("isUsed", 0);
			map.put("endTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			for (int i = 0; i < productIds.length; i++) {
				map.put("productCategory", productDao.selectProductDetails(Long.parseLong(productIds[i])).getProductCategory());
				map.put("minimumPrice", productTotalPrices[i]);
				List<Coupon> list = couponDao.selectCouponsForPlaceOrder(map);
				for (Coupon coupon : list) {
					if(!hasCoupon(returnList, coupon)){
						returnList.add(coupon);
					}
				}
			}
			for (Coupon coupon : returnList) {
				coupon.setAmount(new BigDecimal(coupon.getPriceExpression()));
				coupon.setStartDate(new SimpleDateFormat("yyyy-MM-dd").format(coupon.getBeginDate()));
				coupon.setIntroduce(coupon.getPrefix());
			}
		}
		return returnList;
	}

	@Override
	public CouponCodeBean selectCouponCodeByCouponIdAndMemberId(Map<String, Object> map) {
		return couponDao.selectCouponCodeByCouponIdAndMemberId(map);
	}

	private Boolean hasCoupon(List<Coupon> list, Coupon newCoupon){
		for (Coupon coupon : list) {
			if(coupon.getId() == newCoupon.getId()){
				return true;
			}
		}
		return false;
	}
}
